import { defineStore } from 'pinia';
import { userApi } from '@/api';

export const useUserStore = defineStore('user', {
  state: () => ({
    users: [],
    loading: false,
    error: null,
  }),
  actions: {
    async fetchUsers() {
      this.loading = true;
      try {
        const res = await userApi.getAll();
        if (res.code === 0) {
          this.users = res.data;
        } else {
          this.error = res.message;
        }
      } catch (e) {
        this.error = e.message;
      } finally {
        this.loading = false;
      }
    },
    async addUser(user) {
      this.loading = true;
      try {
        const res = await userApi.add(user);
        if (res.code === 0) {
          await this.fetchUsers();
        } else {
          throw new Error(res.message);
        }
      } finally {
        this.loading = false;
      }
    },
    async updateUser(id, user) {
      this.loading = true;
      try {
        const res = await userApi.update(id, user);
        if (res.code === 0) {
          await this.fetchUsers();
        } else {
          throw new Error(res.message);
        }
      } finally {
        this.loading = false;
      }
    },
    async deleteUser(id) {
      this.loading = true;
      try {
        const res = await userApi.delete(id);
        if (res.code === 0) {
          await this.fetchUsers();
        } else {
          throw new Error(res.message);
        }
      } finally {
        this.loading = false;
      }
    },
  },
}); 